package com.wutongyu.mannyburger;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private BGMService bgmService;
    private boolean isBound = false;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BGMService.LocalBinder binder = (BGMService.LocalBinder) service;
            bgmService = binder.getService();
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    private WifiStateReceiver wifiStateReceiver;

    private com.google.android.material.bottomnavigation.BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView = findViewById(R.id.bottom_navigation);

        bottomNavigationView.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            int itemId = item.getItemId();

            try {
                if (itemId == R.id.navigation_home) {
                    selectedFragment = new HomeFragment();
                } else if (itemId == R.id.navigation_order) {
                    selectedFragment = new OrderFragment();
                } else if (itemId == R.id.navigation_account) {
                    selectedFragment = new LoginFragment();
                }

                if (selectedFragment != null) {
                    loadFragment(selectedFragment);
                    return true;
                }
            } catch (Exception e) {
                Log.e(TAG, "底部导航切换出错: " + e.getMessage(), e);
                Toast.makeText(this, "应用发生错误，请稍后再试", Toast.LENGTH_SHORT).show();
                
                // 尝试回到默认的首页
                try {
                    loadFragment(new HomeFragment());
                } catch (Exception fallbackEx) {
                    Log.e(TAG, "回退到首页面失败", fallbackEx);
                }
                return true;
            }
            return false;
        });

        if (savedInstanceState == null) {
            try {
                bottomNavigationView.setSelectedItemId(R.id.navigation_home);
                loadFragment(new HomeFragment());
            } catch (Exception e) {
                Log.e(TAG, "初始化默认页面出错: " + e.getMessage(), e);
                Toast.makeText(this, "应用初始化错误", Toast.LENGTH_SHORT).show();
            }
        }

        Intent intent = new Intent(this, BGMService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

        wifiStateReceiver = new WifiStateReceiver();
        IntentFilter filter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
        registerReceiver(wifiStateReceiver, filter);
    }

    private void loadFragment(Fragment fragment) {
        try {
            if (isFinishing() || isDestroyed()) {
                Log.w(TAG, "Activity已销毁或正在销毁，取消Fragment加载");
                return;
            }
            
            FragmentManager fragmentManager = getSupportFragmentManager();
            if (fragmentManager.isStateSaved()) {
                Log.w(TAG, "FragmentManager状态已保存，取消Fragment加载");
                return;
            }
            
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.nav_host_fragment_container, fragment);
            
            // 使用commitAllowingStateLoss以避免可能的IllegalStateException
            transaction.commitAllowingStateLoss();
        } catch (Exception e) {
            Log.e(TAG, "加载Fragment出错: " + e.getMessage(), e);
            Toast.makeText(this, "页面加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wifiStateReceiver != null) {
            try {
                unregisterReceiver(wifiStateReceiver);
                wifiStateReceiver = null;
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "广播接收器未注册或已注销", e);
            }
        }
    }

    public void startVideoPlayActivity(String videoPath) {
        if (videoPath == null || videoPath.isEmpty()) {
            Log.w(TAG, "视频路径无效，无法播放。");
            Toast.makeText(this, "无效的视频路径", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            Intent intent = new Intent(this, VideoPlayActivity.class);
            intent.putExtra("videoPath", videoPath);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "启动 VideoPlayActivity 时出错", e);
            Toast.makeText(this, "无法播放视频", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 控制背景音乐播放
     */
    public void playMusic() {
        if (isBound && bgmService != null) {
            bgmService.playMusic();
            Log.d(TAG, "播放背景音乐");
        } else {
            Log.w(TAG, "无法播放音乐，服务未绑定");
            // 尝试重新绑定服务
            Intent intent = new Intent(this, BGMService.class);
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }
    
    /**
     * 暂停背景音乐
     */
    public void pauseMusic() {
        if (isBound && bgmService != null) {
            bgmService.pauseMusic();
            Log.d(TAG, "暂停背景音乐");
        } else {
            Log.w(TAG, "无法暂停音乐，服务未绑定");
        }
    }
    
    /**
     * 检查音乐是否正在播放
     */
    public boolean isMusicPlaying() {
        if (isBound && bgmService != null) {
            return bgmService.isPlaying();
        }
        return false;
    }

    /**
     * 导航到指定的底部导航栏选项卡
     * @param tabId 要切换到的选项卡ID，如R.id.navigation_home，R.id.navigation_order等
     */
    public void navigateToTab(int tabId) {
        if (bottomNavigationView != null) {
            bottomNavigationView.setSelectedItemId(tabId);
        }
    }
}